<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>jsPlumb Demo</title>
<link rel="stylesheet" href="../css/style.css">
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css" type="text/css" media="all" />
<script src="../script/libs/modernizr-2.0.6.min.js"></script>
<style>
div#main {
    padding: 1em;
}

table#layout {
    width: 100%;
    height: 30em;
    margin: 1em;
}

table#layout td div.canvas-container {
    overflow: auto;
    max-width: 500px;
    height: 30em;
}

#canvas {
    position: relative; /* must set to relative to support draggable */
    background-color: #eee;
    width: 3000px;
    height: 100%;
}

#grid {
    background-color: #999;
    height: 100%;
}

.table-node {
    position: absolute; /* must set to absolute to support draggable */
    background-color: #F2FFE1;
    border: 1px solid #83D13D;
    width: 10em;
    opacity: 0.8;
}

.ui-dialog .ui-dialog-title {
    overflow: hidden;
    margin-right: 32px;
}

.ui-dialog .ui-dialog-titlebar-add {
    position: absolute;
    text-decoration: none;
    right: 1.2em;
    top: 50%;
    width: 19px;
    margin: -10px 0 0 0;
    padding: 1px;
    height: 18px;
}

.ui-dialog .ui-dialog-titlebar-add span {
    display: block;
}

.table-node ul {
    list-style: none;
    margin: 0;
    padding: 0;
}

.table-node ul li {
    margin: 0.2em;
    color: blue;
}

.toFront {
    z-index: 2000 !important;
    background-color: #61D8A2;
}

.dragActive {
    border: 2px dotted blue;
    background-color: #61D8A2;
}

.dropHover { border: 1px dotted green; }


</style>
</head>
<body onunload="jsPlumb.unload();">
  <div id="container">
    <header>
      <hgroup>
        <h1>jsPlumb Demo</h1>
        <h2 id="version">Unknown jQuery Version</h2>
        <h2 id="ui-version">Unknown jQuery UI Version</h2>
      </hgroup>

      <nav>
        <ul>
          <li><a href="#">Home</a></li>
          <li><a href="#">About</a></li>
          <li><a href="#">Services</a></li>
          <li><a href="#">Contact</a></li>
        </ul>
      </nav>
    </header>

    <div id="main" role="main">
      <p>God helps those who help themselves.</p>
      <div>
        <button id="addReport">Add a report</button>
        <button id="add">Add a table</button>
      </div>
      <table id="layout" border="1">
        <tbody>
          <tr>
            <td width="30%">
              <div id="report-canvas">Reports</div>
            </td>
            <td width="30%">
              <div class="canvas-container">
                <div id="canvas">Tables</div>
              </div>
            </td>
            <td width="40%">
              <div class="canvas-container">
                <div id="grid">Grid</div>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <div id="template-ReportNode" class="report-node ui-dialog">
      <div class="ui-dialog-titlebar ui-widget-header ui-helper-clearfix">
        <span class="ui-dialog-title">{Report Name}</span>
        <a href="#" class="ui-dialog-titlebar-close ui-corner-all" title="Remove this table">
          <span class="ui-icon ui-icon-closethick">close</span>
        </a>
      </div>
    </div>

    <div id="template-TableNode" class="table-node ui-dialog">
      <div class="ui-dialog-titlebar ui-widget-header ui-helper-clearfix">
        <span class="ui-dialog-title">{Table Name}</span>
        <a href="#" class="ui-dialog-titlebar-add ui-corner-all" title="Add a table to join">
          <span class="">+</span>
        </a>
        <a href="#" class="ui-dialog-titlebar-close ui-corner-all" title="Remove this table">
          <span class="ui-icon ui-icon-closethick">close</span>
        </a>
      </div>
      <div class="ui-dialog-content ui-widget-content">
        <ul class="table-column-list">
          <li>Field 1</li>
          <li>Field 2</li>
        </ul>
      </div>
    </div>

    <footer>
      <div>Copyright &copy; 2011. All rights reserved.</div>
    </footer>
  </div> <!--! end of #container -->

  <script src="../script/libs/jquery-1.6.2.js"></script>
  <script>window.jQuery || document.write('<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"><\/script>')</script>
  <script src="../script/libs/jquery-ui-1.8.16.js"></script>
  <script>window.jQuery.ui || document.write('<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"><\/script>')</script>
  <script src="../script/libs/jquery.jsPlumb-1.3.3-all.js"></script>

  <!-- scripts concatenated and minified via ant build script-->
  <script defer src="../script/plugins.js"></script>
  <!-- end scripts-->

  <script>
    var endpointOptions = {
        isSource: true,
        isTarget: true,
        //dynamicAnchors: ['BottomCenter', 'TopCenter', 'LeftMiddle', 'RightMiddle'],
        maxConnections: -1,
        dropOptions: {
            tolerance: 'touch',
            hoverClass: 'dropHover',
            activeClass: 'dragActive'
        },
        dragAllowedWhenFull: true
    };

    var tableNodeConnections = [];
    function createTableNode() {
        var _d = $('#template-TableNode').clone();
        var tableNodeId = '' + (new Date().getMilliseconds());
        _d.attr('id', tableNodeId).appendTo('#canvas').find('.ui-dialog-title').html(tableNodeId);

        // add icon click handler
        _d.find('a.ui-dialog-titlebar-add').click(function(event) {
            event.preventDefault();

            var sourceTableNodeId = $(this).parents('.table-node').attr('id');
            addJoinedTable(sourceTableNodeId);
        });

        // remove icon click handler
        _d.find('a.ui-dialog-titlebar-close').click(function(event) {
            event.preventDefault();

            var tableNodeId = $(this).parents('.table-node').attr('id');

            // remove endpoints and connections
            jsPlumb.removeAllEndpoints(tableNodeId);

            // remove table node
            $('#' + tableNodeId).remove();
        });

        // make table node draggable
        jsPlumb.draggable(tableNodeId, {
            opacity: 0.5, // Opacity for the helper while being dragged.
            containment: '#canvas', // always inside the canvas
            stack: '#canvas .table-node', // always brings to front the dragged item
            cancel: '.table-column-list',
            scroll: true,
            start: function(event, ui) {
                $(this).toggleClass('dragActive', true);
            },
            stop: function(event, ui) {
                $(this).toggleClass('dragActive', false);
            }
        });

        // make table column item draggable
        $('#' + tableNodeId + ' .table-column-list > li').draggable({
            opacity: 1, // Opacity for the helper while being dragged.
            appendTo: 'body',
            helper: 'clone'
        });

        // resizable
        $('#' + tableNodeId).resizable({
            minHeight: 100,
            minWidth: 100,
            resize: function(event, ui) {
                jsPlumb.repaint($(this));
            }
        });

        // hover
        $('#' + tableNodeId).hover(
                function() { $(this).addClass('toFront'); },
                function() { $(this).removeClass('toFront'); }
        );

        return {d: _d, id: tableNodeId};
    }

    function prepare(elId) {
        //jsPlumbDemo.initHover(elId);
        //jsPlumbDemo.initAnimation(elId);

        return jsPlumb.addEndpoint(elId, endpointOptions);
    }

    function addJoinedTable(sourceTableNodeId) {
        var joinedTableNodeInfo = createTableNode();
        var targetTableNodeId = joinedTableNodeInfo.id;

        // adujst position for target node
        //var left = $('#' + sourceTableNodeId).css('left') || 0;
        //var top = $('#' + sourceTableNodeId).css('top') || 0;
        var sourcePosition = $('#' + sourceTableNodeId).position();
        var offset = 10;
        $('#' + targetTableNodeId).css({
            'left': sourcePosition.left + offset,
            'top': sourcePosition.top + offset
        });

        // connect
        jsPlumb.connect({
            source: sourceTableNodeId,
            target: targetTableNodeId
        });

        // bring target table node to front
        $('#' + targetTableNodeId).css('z-index', 2000);

        // save connection
        tableNodeConnections.push();
    }

    function initAddReportButton() {
        $('#addReport').button();
        $('#addReport').click(function(event, ui) {
            alert('unimplemented!');
        });
    }

    function initAddButton() {
        $('#add').button();

        var _addButtonClickHandler = function(event) {
            event.preventDefault();

            createTableNode();
        };
        $('#add').unbind('click', _addButtonClickHandler);
        $('#add').bind('click', _addButtonClickHandler);
    }
  </script>
  <script>
    $(document).ready(function() {
        // version
        var version = $.fn.jquery;
        $('#version').html('jQuery: ' + version);
        var uiVersion = $.ui.version;
        $('#ui-version').html('jQuery UI: ' + uiVersion);

        // hide
        //$('nav').toggle(false);
        $('nav li').draggable({
            opacity: 0.5, // Opacity for the helper while being dragged.
            containment: 'parent',
            scroll: false,
            helper: 'clone'
        });

        // jsPlumb
        // chrome fix.
        document.onselectstart = function () { return false; };

        jsPlumb.setRenderMode(jsPlumb.SVG);
        jsPlumb.Defaults.Anchor = 'AutoDefault';
        jsPlumb.Defaults.Connector = ['Bezier', {curviness: 50}];
        jsPlumb.Defaults.DragOptions = {cursor: 'pointer', zIndex: 2000};
        jsPlumb.Defaults.Endpoint = 'Dot';
        jsPlumb.Defaults.EndpointStyle = {radius: 5, fillStyle: 'gray'};
        jsPlumb.Defaults.PaintStyle = {strokeStyle: 'gray', lineWidth: 2};
        jsPlumb.Defaults.Overlays = [
            ['Arrow', {width: 10, length: 16, location: 1}]
        ];

        // add
        initAddReportButton();
        initAddButton();

        // drop grip
        $('#grid').droppable({
            hoverClass: 'ui-state-hover',
            activeClass: "ui-state-active",
            drop: function(event, ui) {
                $('<li></li>').text(ui.draggable.text()).appendTo(this);
            }
        });
    });
  </script>
</body>
</html>